﻿using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using System;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

namespace PromotedLinks.PromotedLinksPart
{
    [ToolboxItemAttribute(false)]
    public partial class PromotedLinksPart : WebPart
    {
        [WebBrowsable(true)]
        [Browsable(true)]
        [Category("Settings")]
        [DisplayName("Promoted links list name")]
        [Personalizable(PersonalizationScope.Shared)]
        public string ListName { get; set; }

        [WebBrowsable(true)]
        [Browsable(true)]
        [Category("Settings")]
        [DisplayName("Try to use dynamic linking")]
        [Personalizable(PersonalizationScope.Shared)]
        public bool DynamicLinks { get; set; }

        [WebBrowsable(true)]
        [Browsable(true)]
        [Category("Style")]
        [DisplayName("Tile Width")]
        [DefaultValue(150)]
        [Personalizable(PersonalizationScope.Shared)]
        public int TileWidth { get; set; }

        [WebBrowsable(true)]
        [Browsable(true)]
        [Category("Style")]
        [DisplayName("Tile Height")]
        [DefaultValue(150)]
        [Personalizable(PersonalizationScope.Shared)]
        public int TileHeight { get; set; }

        [WebBrowsable(true)]
        [Browsable(true)]
        [Category("Style")]
        [DisplayName("Background Color")]
        [DefaultValue("#0072C6")]
        [Personalizable(PersonalizationScope.Shared)]
        public string BackgroundColor { get; set; }

        public int TotalHeight = 160;
        public int TotalWidth = 160;
        public int CollapsedTop = 100;

        // Uncomment the following SecurityPermission attribute only when doing Performance Profiling on a farm solution
        // using the Instrumentation method, and then remove the SecurityPermission attribute when the code is ready
        // for production. Because the SecurityPermission attribute bypasses the security check for callers of
        // your constructor, it's not recommended for production purposes.
        // [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Assert, UnmanagedCode = true)]
        public PromotedLinksPart()
        {
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            InitializeControl();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            TotalHeight = TileHeight + 10;
            TotalWidth = TileWidth + 10;
            CollapsedTop = (int)Math.Round(TileHeight * 0.66, 0);

            SPList promotedLinks = SPContext.Current.Web.Lists.TryGetList(ListName);

            if (promotedLinks != null)
            {
                SPQuery qry = new SPQuery();
                qry.Query = "<OrderBy><FieldRef Name='TileOrder' Ascending='TRUE' /></OrderBy>";
                rptTiles.DataSource = promotedLinks.GetItems(qry);
                rptTiles.DataBind();
            }
        }

        protected void rptTiles_ItemDataBound(object sender, System.Web.UI.WebControls.RepeaterItemEventArgs e)
        {
            if ((e.Item != null) && (e.Item.DataItem != null))
            {
                SPListItem itm = e.Item.DataItem as SPListItem;

                if (itm != null)
                {
                    HtmlAnchor tileLink = e.Item.FindControl("tileLink") as HtmlAnchor;

                    if (tileLink != null)
                    {
                        string linkValue = GetURLValue(itm, "LinkLocation");

                        if (linkValue != null)
                        {
                            if (linkValue.Contains("http") || linkValue.Contains("ftp") || linkValue.Contains("file"))
                            {
                                if(linkValue.Contains("http") && DynamicLinks)
                                {
                                    try 
	                                {
                                        using (SPSite site = new SPSite(linkValue))
                                        {
                                            using (SPWeb web = site.OpenWeb())
                                            {
                                                linkValue.Replace(web.Url, SPContext.Current.Web.Url);
                                            }
                                        }
	                                }
	                                catch (Exception)
	                                {
	                                }
                                }

                                if (GetStringValue(itm, "LaunchBehavior").Contains("In page navigation"))
                                {
                                    tileLink.Attributes.Add("onclick", "javascript:window.location.href=" + linkValue + "; return false;");
                                    tileLink.HRef = linkValue;
                                }
                                else if (GetStringValue(itm, "LaunchBehavior").Contains("New tab"))
                                {
                                    tileLink.Attributes.Add("target", "_blank");
                                    tileLink.HRef = linkValue;
                                }
                                else if (GetStringValue(itm, "LaunchBehavior").Contains("Dialog"))
                                {
                                    if (linkValue.Contains("?"))
                                    {
                                        tileLink.Attributes.Add("onclick", "javascript:SP.UI.ModalDialog.showModalDialog({ url: '" + linkValue + "&IsDlg=1', title: '" + itm.Title + "' }); return false;");
                                    }
                                    else
                                    {
                                        tileLink.Attributes.Add("onclick", "javascript:SP.UI.ModalDialog.showModalDialog({ url: '" + linkValue + "?IsDlg=1', title: '" + itm.Title + "' }); return false;");
                                    }

                                    tileLink.HRef = "#";
                                }
                            }
                            else
                            {
                                if (DynamicLinks)
                                {
                                    try
                                    {
                                        using (SPSite site = new SPSite(linkValue))
                                        {
                                            using (SPWeb web = site.OpenWeb())
                                            {
                                                linkValue.Replace(web.Url.Replace("http://", ""), SPContext.Current.Web.Url);
                                            }
                                        }
                                    }
                                    catch (Exception)
                                    {
                                    }
                                }

                                tileLink.Attributes.Add("onclick", "javascript:window.location.href=_spPageContextInfo.webAbsoluteUrl + '" + linkValue + "'; return false;");
                                tileLink.HRef = "javascript:window.location.href=_spPageContextInfo.webAbsoluteUrl + '" + linkValue + "'; return false;";
                            }
                        }
                    }

                    HtmlImage tileImage = e.Item.FindControl("tileImage") as HtmlImage;

                    if (tileImage != null)
                    {
                        tileImage.Src = GetURLValue(itm, "BackgroundImageLocation");
                    }

                    HtmlGenericControl tileTitle = e.Item.FindControl("tileTitle") as HtmlGenericControl;
                    if (tileTitle != null)
                    {
                        tileTitle.InnerHtml = itm.Title;
                    }

                    HtmlGenericControl tileDescription = e.Item.FindControl("tileDescription") as HtmlGenericControl;
                    if (tileDescription != null)
                    {
                        tileDescription.InnerHtml = GetStringValue(itm, "Description");
                    }
                }
                else
                {
                    e.Item.Visible = false;
                }
            }
        }

        private string GetURLValue(SPListItem itm, string fieldName)
        {
            string returnValue = string.Empty;
            SPField fld = itm.Fields.GetFieldByInternalName(fieldName);

            if (fld != null)
            {
                if (itm[fld.Id] != null)
                {
                    SPFieldUrlValue urlValue = new SPFieldUrlValue(itm[fld.Id].ToString());
                    returnValue = urlValue.Url;
                }
            }

            return returnValue;
        }

        private string GetStringValue(SPListItem itm, string fieldName)
        {
            string returnValue = string.Empty;
            SPField fld = itm.Fields.GetFieldByInternalName(fieldName);

            if (fld != null)
            {
                if (itm[fld.Id] != null)
                {
                    returnValue = itm[fld.Id].ToString();
                }
            }

            return returnValue;
        }
    }
}
